<template>
  <!-- 添加按钮 -->
  <el-button type="success" @click="addRole()">添加</el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="id" label="id" width="150"/>
    <el-table-column prop="username" label="名字" width="150"/>
    <el-table-column prop="tel" label="手机" width="150">
<!--      this.originalPhoneNumber.replace(/(\d{3})\d*(\d{4})/, '$1****$2');-->
      <template #default="scope">
        {{scope.row.tel.replace(/(\d{3})\d*(\d{4})/, '$1****$2')}}
      </template>
    </el-table-column>
    <el-table-column label="Operations" min-width="120">
      <!-- scope代表的是当前的表格 -->
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleClick(scope.row.id)">
          删除
        </el-button>
        <el-button link type="primary" size="small"  @click="updRole(scope.row)">修改</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--  分页开始 -->
  <div class="demo-pagination-block">

    <el-pagination
        :current-page="page.currentPage"
        :page-size="page.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!-- 分页结束 -->

  <!--  模态框开始 -->
  <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="500"
  >
    <span>
       <!-- 模态框中的内容开始 -->
       <el-form
           ref="ruleFormRef"
           style="max-width: 600px"
           :model="ruleForm"
           :rules="rules"
           label-width="auto"
           class="demo-ruleForm"
           status-icon
       >
    <el-form-item label="名字" prop="stuname">
      <el-input v-model="ruleForm.username"/>
    </el-form-item>

<!--  角色的信息        -->
   <el-form-item label="角色">
      <el-checkbox-group v-model="ruleForm.permissions">

           <el-checkbox v-for="item in roles" :key="item.id" :value="item.id" name="rolename">
                {{item.rname}}
           </el-checkbox>
      </el-checkbox-group>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleFormRef')">
        提交
      </el-button>
      <el-button @click="resetForm('ruleFormRef')">取消</el-button>
    </el-form-item>
  </el-form>

      <!-- 模态框中的内容结束 -->
    </span>

  </el-dialog>

  <!-- 模态框结束 -->

</template>

<script>
// 前后端交互   axios
import {
  Search
} from '@element-plus/icons-vue';
// import axios from 'axios';
import {ElMessage, ElMessageBox} from 'element-plus';

export default {
  computed: {
    Search() {
      return Search
    },

  },
  data() {
    return {
      value:{},
      roles:[],
      ruleForm: {
        username: "",
        permissions:[]

      },
      rules: {
        // 规则
        username: [
          {required: true, message: '请填写名字', trigger: 'blur'},
          {min: 2, max: 10, message: '字符串的长度在2-10之间', trigger: 'blur'},
        ]
      },
      title: "添加员工",
      // 模态框是否弹出
      dialogVisible: false,
      tableData: [],
      page:{
        currentPage: 1,
        pageSize: 2,
        total: 100,
      },
      rname: ""
    }
  },
  methods: {
// 修改:
    updRole(obj){
      // obj 对象  一行的数据
      this.dialogVisible=true;
      //console.log(obj);
      this.title="修改角色";
     // alert(obj.id);
      // 深拷贝
      this.ruleForm=JSON.parse(JSON.stringify(obj));
      this.ruleForm.permissions=[];
      // 查询当前的用户对应的角色的id
      //
      this.$axios.get(`/tab-user-role?uid=${obj.id}`).then(res=>{
       let userrole= res.data.data;
       //
        for (let i = 0; i < userrole.length; i++) {
          this.ruleForm.permissions.push(userrole[i].rid);
        }

      })




    },


    // 提交表单
    // 校验通过之后 才可以提交
    submitForm(formName) {

      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 把数据提交到数据库里面   controller
          // 添加 post请求

         //alert(JSON.stringify(this.ruleForm));
          // axios 发出一个post请求
          this.$axios.post("/tab-user",this.ruleForm).then(res=>{
            ElMessage({
              type: 'success',
              message: '添加成功',
            })

            // 关闭当前的模态框
            this.dialogVisible=false;
            this.queryTableData();

          })

        } else {
         alert('error submit!!');
          return false;
        }
      });


  },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 添加角色
    addRole() {
      //alert("弹出一个form表单");
      // dialogVisible 设置为true
      this.dialogVisible = true;
      this.ruleForm={
        username: "",
         permissions: []
      }
    },


    // 页数发生更改
    handleCurrentChange(val) {

      //alert(`当前的的页数:${val}`)
      this.page.currentPage = val;
      this.queryTableData();
    },
    handleClick(id) {
      // alert(id);


      ElMessageBox.confirm(
          '您确定要删除吗',
          '警告',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            // alert(obj.row.id)
            // 后台请求删除
            this.$axios.delete("/tab-stu?id=" + id).then(res => {
              // alert(res.data.code);
              // 刷新页面
              this.queryTableData();
              ElMessage({
                type: 'success',
                message: '删除成功',
              })

            })


          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: 'Delete canceled',
            })
          })

    },
    handleSizeChange(val) {
      // alert(`每页显示的条数是:${val}`)
      this.page.pageSize = val;
      this.queryTableData();
    },
    queryTableData() {
      // 获取下拉框中的值
      //alert(JSON.stringify(this.value));
      // params:{
      //   currentPage:1,
      // pageSize:2,
      //    cid:
      //cname:
      //
      // }
      // 扩展运算符  ...


      //alert(JSON.stringify(newobj));
      this.$axios.get("/tab-user",{params:this.page}).then(res=>{
       // console.log(res.data.data);
        this.tableData=res.data.data.records;
        //

        this.page.total=res.data.data.total;


      })

    }
    ,
    queryRoleData() {
      this.$axios.get("/tab-role",{params:{
          currPage:1,
          pageSize:100
        }}).then(res=>{

          console.log(res.data.data.records);
          this.roles=res.data.data.records;



      })
    }
  },
  created() {


    this.queryTableData();
    this.queryRoleData();

  },
}


</script>